package com.bioroadlab.dao;

import java.io.File;
import java.io.IOException;
import java.util.List;

import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.cn.smart.SmartChineseAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.document.FieldType;
import org.apache.lucene.document.IntField;
import org.apache.lucene.document.FieldType.NumericType;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.IndexWriterConfig;
import org.apache.lucene.index.IndexWriterConfig.OpenMode;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.FSDirectory;
import org.apache.lucene.util.Version;
import org.hibernate.Query;
import org.springframework.stereotype.Repository;

import com.bioroadlab.pojo.DiseaseKeyword;

@Repository
public class DiseaseKeywordDao extends BaseDao<DiseaseKeyword, Integer> {

	public int indexFileForDiseaseKeyword(String indexDir) throws IOException {
		Analyzer sa = new SmartChineseAnalyzer(Version.LUCENE_40);
		IndexWriterConfig iwc = new IndexWriterConfig(Version.LUCENE_40, sa);
		iwc.setOpenMode(OpenMode.CREATE);
		Directory dir = FSDirectory.open(new File(indexDir));
		IndexWriter writer = new IndexWriter(dir, iwc);
		int numIndexed = -1;
		try {
			String hql = "from DiseaseKeyword";
			Query query = getSession().createQuery(hql);
			@SuppressWarnings("unchecked")
			List<DiseaseKeyword> diseaseKeywordList = (List<DiseaseKeyword>) query
					.list();
			DiseaseKeyword[] diseaseKeywordArray = (DiseaseKeyword[]) diseaseKeywordList
					.toArray(new DiseaseKeyword[diseaseKeywordList.size()]);
			FieldType ft = new FieldType();
			ft.setIndexed(true);

			ft.setTokenized(true);
			ft.setStored(true);
			FieldType ft2 = new FieldType();
			ft2.setNumericType(NumericType.INT);
			ft2.setIndexed(false);
			ft2.setStored(true);
			for (int i = 0; i < diseaseKeywordArray.length; i++) {
				Document doc = new Document();
				doc.add(new IntField("sn", diseaseKeywordArray[i].getSn(), ft2));
				doc.add(new Field("name", String.valueOf(diseaseKeywordArray[i]
						.getName()), ft));
				writer.addDocument(doc);
			}

			numIndexed = writer.maxDoc();// .docCount();
		} finally {
			writer.close();
		}
		return numIndexed;
	}

}
